/**
 * Created by Administrator on 2017/1/10.
 */


global.logger = require('pomelo-logger').getLogger('world');

var GlobalConfig = require('../../../config/config.json');

global.DB = require('../../util/mongodb.js');
global.SQL = require('../../util/mysql.js');
global.Redis = null;

var GlobalManager = require('./GlobalManager').GlobalManager;
var CheckSignManager = require('./checkSignManager').CheckSignManager;
var SessionManager = require('./sessionManager').SessionManager;
var PlayerManager = require('./playerManager').PlayerManager;
var RobotManager = require('./RobotManager').RobotManager;
var GroupManager = require('./GroupManager').GroupManager;
var MatchManager = require('./matchManager').MatchManager;



global.gCheckSignManager = new CheckSignManager();
global.gSessionManager = new SessionManager();
global.gPlayerManger = new PlayerManager();
global.gRobotManager = new RobotManager();
global.gGlobalManager = new GlobalManager();
global.gGroupManager = new GroupManager();
global.gMatchManager = new MatchManager();


var utilRedis = require('../../util/redis.js');

var gmServer = require('../gm/gm');
var apiServer = require('../api/api');

module.exports = {
    init: function() {
        async.series([
            function(cb) {
                DB.loadDB(function(err) {
                    if (err) {
                        logger.error("db load failed: %j", err);
                    }
                    cb(err);
                });
            },
            function(cb) {
                DB.initDB(function(err) {
                    if (err) {
                        logger.error("db init failed: %j", err);
                    }
                    cb(err);
                });
            },
            function(cb) {
                SQL.init(function(err) {
                    if (err) {
                        logger.error("mysql init failed: %j", err.stack);
                    }
                    cb(err);
                });
            },
            function(cb) {
                utilRedis.loadDB(function(err, client) {
                    global.Redis = client;
                    cb(err);
                });
            },
            function(cb) {
                gPlayerManger.init(cb);
            },
            function(cb) { // 添加默认管理员账号
                gPlayerManger.addPlat("BYY:GM:" + Def.GM_LEVEL_SUPER, function(err, uid) {
                    if(err)
                        console.log("add Managers")
                    cb(err);
                });
            },
            function(cb) {
                var uid = GlobalConfig.logic.minUid + 1;
                gPlayerManger.getPlayer(uid, function(player) {
                    if (!player) {
                        console.log("have not player")
                        cb(Code.DB_ERROR); return;
                    }

                    if (player.isNew) {
                        var user = player.user;
                        user.info.name = "Admin";
                        user.info.createIP = "127.0.0.1";
                        player.markDirty("info");
                        player.setGmLevel(Def.GM_LEVEL_SUPER);
                        player.save(true);
                        player.isNew = false;
                    } else {
                        if (player.isRobot()) {
                            player.user.robot = 0;
                            player.markDirty("robot");
                            player.save(true);
                        }
                    }

                    cb();
                });
            },
            function(cb) {
                gGlobalManager.init(cb);
            },
            function(cb) {
                gRobotManager.init(cb);
            },function (cb) {
                gGroupManager.init(cb);
            },function (cb) {
                gCheckSignManager.init(cb);
            }, function(cb) {
                gMatchManager.init(cb);
            },
            function(cb) {
                gmServer.start(function(err) {
                    if (err) {
                        logger.error("gm start failed: %j", err);
                        cb(err);
                    }

                    logger.info('gm start success');
                    cb();
                });
            },
            function(cb) {
                apiServer.start(function(err) {
                    if (err) {
                        logger.error("api start failed: %j", err);
                        cb(err);
                    }

                    logger.info('api start success');
                    cb();
                });
            },
        ], function(err) {
            if (err) {
                logger.error("world init failed: %j", err);
                process.exit(-1);
            }

            setInterval(function() {
                gRobotManager.tick();
                gPlayerManger.tick();
            }, 1*1000);

            setInterval(function() {
                gPlayerManger.saveAll(false, function() {});
                gGlobalManager.saveAll(function() {});
            }, 60*1000);

            logger.info('world init success');
        });
    },

    stop: function(callback) {
        async.series([
            function(cb) {
                gPlayerManger.saveAll(true, function() {
                    cb();
                });
            },
            function(cb) {
                gGlobalManager.saveAll(function() {
                    cb();
                });
            },
            function(cb) {
                gmServer.stop(function(err) {
                    cb();
                })
            },
        ], function(err) {
            logger.info('world stop success');
            callback && callback();
        });
    }
}